package com.cloud.other;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @Author tangyuan2meicloud.com
 * @DATE 2021/7/2 22:55
 * @Desc
 * @Remarks
 */
//@Component
public class TyDefineRoutePredicateFactory extends AbstractRoutePredicateFactory<TyDefineRoutePredicateFactory.Config> {

    public static final String NAME_KEY = "name";

    public static final String VALUE_KEY = "value";

    public TyDefineRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange exchange) {
                List<String> list = exchange.getRequest().getHeaders().get(config.name);
                if (list != null && list.size() == 1 && config.value.equals(list.get(0))) {
                    return true;
                }
                return false;
            }
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(NAME_KEY, VALUE_KEY);
    }

    public static class Config {

        private String name;

        private String value;

        public String getName() {
            return name;
        }

        public String getValue() {
            return value;
        }

        public TyDefineRoutePredicateFactory.Config setName(String name) {
            this.name = name;
            return this;
        }

        public TyDefineRoutePredicateFactory.Config setValue(String value) {
            this.value = value;
            return this;
        }
    }
}
